package com.hm.shopping.api;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.hm.common.oss.qiniu.su.QiNiuHandlerSupport;
import com.hm.common.util.FileUtil;
import com.hm.shopping.auto.su.BaseController;
import com.hm.shopping.auto.su.R.Restful;

import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * @author shishun.wang
 * @date 2018年2月8日 下午3:35:36
 * @version 1.0
 * @describe 
 */
@Slf4j
@ResponseBody
@RestController
@RequestMapping(Restful.API + "/common")
public class CommonAction extends BaseController {

	@Autowired
	private QiNiuHandlerSupport qiNiuHandlerSupport;
	
	private static final String SWWAGER_TAG = "公共组件管理";

	@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
	@ApiOperation(tags = SWWAGER_TAG, value = "文件上传", httpMethod = "GET", notes = "com.hm.shopping.api.CommonAction::uploadFile")
	public void uploadFile(@RequestParam("file") MultipartFile file) {
		try {
			String filename = file.getOriginalFilename();
			String suffix = filename.substring(filename.lastIndexOf(".") + 1, filename.length());
			File tempFile = File.createTempFile(filename, suffix);
			tempFile.deleteOnExit();
			file.transferTo(tempFile);
			byte[] datas = FileUtil.getFile(tempFile);
			String uploadFileUri = qiNiuHandlerSupport.buildSampleHandler().upload(System.nanoTime() + "." + suffix, datas);
			
			Map<String,String> content = new HashMap<String,String>();
			content.put("link", uploadFileUri);
			
			super.putJson(content);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			super.failure(e.getMessage());
		}
	}
}
